<?php
App::uses('AppController', 'Controller');
/**
 * Products Controller
 *
 * @property Product $Product
 * @property PaginatorComponent $Paginator
 */
class ProductsController extends AppController {

/**
 * Components
 *
 * @var array
 */
	 public $components = array(
                'Session',
                'Paginator',
                'Auth' => array(
                    'authorize' => array('Controller'),
                    'loginAction' => array('controller' => 'pages', 'action' => 'login'),
                    'loginRedirect' => array('controller' => 'students', 'action' => 'index'),
                    'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home')
                ),
                'Cookie' => array('name' => 'CookieMonster')
    );

    public $helpers = array('Form', 'Html', 'Js', 'Time','Session');
  public function isAuthorized($user) {
                return true;
        }
  public function beforeFilter() {
        $this->Auth->allow('index','add','edit','delete','smart_resize_image');
         if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){ 
              $this->layout='default';
         } else {
            $this->layout='home';
         }  
           Controller::loadModel('Menu');
                  $this->set('menus', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'0'), 'order' => array('Menu.order' => 'asc'))));
                 $this->set('menusbottom', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'1'), 'order' => array('Menu.order' => 'asc'))));
                  $this->set('menusleft', $this->Menu->Find('all', array('conditions'=>array('Menu.position'=>'2'), 'order' => array('Menu.order' => 'asc'))));
                  Controller::loadModel('Category');
         Controller::loadModel('Location');
        $nodelist = $this->Category->generateTreeList(null,null,null," - ");

//      $this->set('parents',$this->Category->generatetreelist());
        $this->set('parents',($nodelist));
        $categories = $this->Category->find('list');
        $locations = $this->Location->find('list');
        $this->set(compact('locations'));
        $this->set('params','');
        
        Controller::loadModel('Paid_ads');
        $myDate = date("Y-m-d");
        // Left Ads
        $leftads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 2, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftbanners', $leftads);

        // Right Ads
        $rightads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 3, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightbanners', $rightads);

        // Top Header Ads
        $topheaderads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 4, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topheaderads', $topheaderads);

        // Top Header Ads
        $bannerads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 5, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bannerads', $bannerads);

        // Top Content Ads
        $topcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 6, 'Paid_ads.expired >=' => $myDate))));
        $this->set('topcontentads', $topcontentads);

        // Top Content Ads
        $middlecontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 7, 'Paid_ads.expired >=' => $myDate))));
        $this->set('middlecontentads', $middlecontentads);

        // Top Content Ads
        $bottomcontentads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 8, 'Paid_ads.expired >=' => $myDate))));
        $this->set('bottomcontentads', $bottomcontentads);
        
        // Left Sidebar Ads
        $leftsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 9, 'Paid_ads.expired >=' => $myDate))));
        $this->set('leftsidebarads', $leftsidebarads);
        
        // Right Sidebar Ads
        $rightsidebarads = $this->Paid_ads->find('all', array('conditions' => array('AND' => array('Paid_ads.position' => 10, 'Paid_ads.expired >=' => $myDate))));
        $this->set('rightsidebarads', $rightsidebarads);
        
         Controller::loadModel('Product');
        if($this->Session->check('order')){
           $data = $this->Session->read('order');
            $favoriteproduct = $this->Product->find('all', array('conditions' => array('Product.id' => $data)));
            $this->set('favoriteproducts', $favoriteproduct);
        }
    }
   

/**
 * index method
 *
 * @return void
 */
	public function index() {
             $this->Paginator->settings = array(
                    'limit' => 8);
            if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
		$this->Product->recursive = 0;
		$this->set('products', $this->Paginator->paginate());
            }
            else {
                return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'index'));
            }
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
            $user=$this->Session->read('facebook');
             if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin' || $user=='facebook'){
		if (!$this->Product->exists($id)) {
			throw new NotFoundException(__('Invalid product'));
		}
		$options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
		$this->set('product', $this->Product->find('first', $options));
             }
             else {
                return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'index'));
            }
	}

/**
 * add method
 *
 * @return void
 */
	public function add($catid=null) {
           $user=$this->Session->read('facebook');
         
           if ($this->Auth->user('role')=='Admin' || $this->Auth->user('role')=='Register' || $user=='facebook'){ 
		if ($this->request->is('post')) {
                  
                        $this->request->data['Product']['posted_date']=date("Y-m-d H:i:s");
                        $this->request->data['Product']['expired_date']=date('Y').'-0'.(date('m')+1).'-'.date("d H:i:s");
                        $this->request->data['Product']['modified_date']=date("Y-m-d H:i:s");
			$this->Product->create();
                        
                        $validate = true;
                            $allowedMime = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/jpg');

                            // Control Picture of Before
                            $requestimage = $this->request->data['Product']['picture1'];

                            if (!empty($requestimage['type']) && in_array($requestimage['type'], $allowedMime)) {
                                $newfilename = date("YmdGis") . $requestimage['name'];
                                if (!move_uploaded_file($requestimage['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename)) {
                                    $this->Product->invalidate('picture1', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture1'] = $newfilename;
                                }
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                            } else {
                                if (!empty($requestimage['tmp_name'])) {
                                    $this->Product->invalidate('picture1', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture1'] = NULL;
                                }
                            }
                            // Control Picture2 of Before
                            $requestimage2 = $this->request->data['Product']['picture2'];

                            if (!empty($requestimage2['type']) && in_array($requestimage2['type'], $allowedMime)) {
                                $newfilename2 = date("YmdGis") . $requestimage2['name'];
                                if (!move_uploaded_file($requestimage2['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename2)) {
                                    $this->Product->invalidate('picture2', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture2'] = $newfilename2;
                                }
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename2;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename2;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                            } else {
                                if (!empty($requestimage2['tmp_name'])) {
                                    $this->Product->invalidate('picture2', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture2'] = NULL;
                                }
                            }
                            // Control Picture3 of Before
                            $requestimage3 = $this->request->data['Product']['picture3'];

                            if (!empty($requestimage3['type']) && in_array($requestimage3['type'], $allowedMime)) {
                                $newfilename3 = date("YmdGis") . $requestimage3['name'];
                                if (!move_uploaded_file($requestimage3['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename3)) {
                                    $this->Product->invalidate('picture3', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture3'] = $newfilename3;
                                }
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename3;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename3;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                            } else {
                                if (!empty($requestimage3['tmp_name'])) {
                                    $this->Product->invalidate('picture3', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture3'] = NULL;
                                }
                            }
                             // Control Picture4 of Before
                            $requestimage4 = $this->request->data['Product']['picture4'];

                            if (!empty($requestimage4['type']) && in_array($requestimage4['type'], $allowedMime)) {
                                $newfilename4 = date("YmdGis") . $requestimage4['name'];
                                if (!move_uploaded_file($requestimage4['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename4)) {
                                    $this->Product->invalidate('picture4', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture4'] = $newfilename4;
                                }
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename4;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename4;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                            } else {
                                if (!empty($requestimage4['tmp_name'])) {
                                    $this->Product->invalidate('picture4', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture4'] = NULL;
                                }
                            }
			 if ($validate && $this->Product->saveAssociated($this->request->data)) {
				$this->Session->setFlash(__('The product has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.'));
			}
		}
                 Controller::loadModel('Category');
                $nodelist = $this->Category->generateTreeList(null,null,null," - ");
               
//			$this->set('parents',$this->Category->generatetreelist());
                $this->set('parents',($nodelist));
		$categories = $this->Product->Category->find('list');
		$users = $this->Product->User->find('list');
		$locations = $this->Product->Location->find('list');
		$this->set(compact('users', 'locations'));
                $this->set('catlist', $this->Category->find('all', array('conditions'=>array('Category.parent_id'=>$catid))));
          
           } else{
                 return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'login'));
            }
           
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
            $user=$this->Session->read('facebook');
            Controller::loadModel('Product');
            if ($this->Auth->user('role')=='Admin' || $this->Auth->user('role')=='Register' || $user=='facebook'){
		if (!$this->Product->exists($id)) {
			throw new NotFoundException(__('Invalid product'));
		}
                $oldProduct = $this->Product->find('all', array('conditions'=>array('Product.id'=>$id)));
		if ($this->request->is(array('post', 'put'))) {
                   
                    $this->Product->create();
                 
                     $validate = true;
                            $allowedMime = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/jpg');

                            // Control Picture of Before
                            $requestimage = $this->request->data['Product']['picture1'];
                            $newfilename = date("YmdGis") . $requestimage['name'];
                            if(!empty($this->request->data['Product']['picture1']['name'])) {
                                $image1 = $newfilename;
                            }else {
                                $image1 = $oldProduct[0]['Product']['picture1'];
                            }

                            if (!empty($requestimage['type']) && in_array($requestimage['type'], $allowedMime)) {
                                if (!move_uploaded_file($requestimage['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename)) {
                                    $this->Product->invalidate('picture1', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture1'] = $newfilename;
                                }
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                                $picture1 = new File(WWW_ROOT ."/img/uploads/images_resize/".$oldProduct[0]['Product']['picture1']);
                                $picture1->delete();
                                $picture1 = new File(WWW_ROOT ."/img/uploads/".$oldProduct[0]['Product']['picture1']);
                                $picture1->delete();
                            } else {
                                if (!empty($requestimage['tmp_name'])) {
                                    $this->Product->invalidate('picture1', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture1'] = NULL;
                                }
                            }
                            // Control Picture2 of Before
                            $requestimage2 = $this->request->data['Product']['picture2'];
                            $newfilename2 = date("YmdGis") . $requestimage2['name'];
                            if(!empty($this->request->data['Product']['picture2']['name'])) {
                                $image2 = $newfilename2;
                            }else {
                                $image2 = $oldProduct[0]['Product']['picture2'];
                            }

                            if (!empty($requestimage2['type']) && in_array($requestimage2['type'], $allowedMime)) {
                                if (!move_uploaded_file($requestimage2['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename2)) {
                                    $this->Product->invalidate('picture2', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture2'] = $newfilename2;
                                }
                                
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename2;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename2;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                                $picture2 = new File(WWW_ROOT ."/img/uploads/images_resize/".$oldProduct[0]['Product']['picture2']);
                                $picture2->delete();
                                $picture2 = new File(WWW_ROOT ."/img/uploads/".$oldProduct[0]['Product']['picture2']);
                                $picture2->delete();
                            } else {
                                if (!empty($requestimage2['tmp_name'])) {
                                    $this->Product->invalidate('picture2', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture2'] = NULL;
                                }
                            }
                            // Control Picture3 of Before
                            $requestimage3 = $this->request->data['Product']['picture3'];
                            $newfilename3 = date("YmdGis") . $requestimage3['name'];
                            if(!empty($this->request->data['Product']['picture3']['name'])) {
                                $image3 = $newfilename3;
                            }else {
                                $image3 = $oldProduct[0]['Product']['picture3'];
                            }

                            if (!empty($requestimage3['type']) && in_array($requestimage3['type'], $allowedMime)) {
                                if (!move_uploaded_file($requestimage3['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename3)) {
                                    $this->Product->invalidate('picture3', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture3'] = $newfilename3;
                                }
                                
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename3;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename3;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                                $picture3 = new File(WWW_ROOT ."/img/uploads/images_resize/".$oldProduct[0]['Product']['picture3']);
                                $picture3->delete();
                                $picture3 = new File(WWW_ROOT ."/img/uploads/".$oldProduct[0]['Product']['picture3']);
                                $picture3->delete();
                            } else {
                                if (!empty($requestimage3['tmp_name'])) {
                                    $this->Product->invalidate('picture3', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture3'] = NULL;
                                }
                            }
                             // Control Picture4 of Before
                            $requestimage4 = $this->request->data['Product']['picture4'];
                            $newfilename4 = date("YmdGis") . $requestimage4['name'];
                            if(!empty($this->request->data['Product']['picture4']['name'])) {
                                $image4 = $newfilename4;
                            }else {
                                $image4 = $oldProduct[0]['Product']['picture4'];
                            }

                            if (!empty($requestimage4['type']) && in_array($requestimage4['type'], $allowedMime)) {
                                if (!move_uploaded_file($requestimage4['tmp_name'], WWW_ROOT . 'img' . DS . 'uploads' . DS . $newfilename4)) {
                                    $this->Product->invalidate('picture4', 'File was not uploaded, please try again.');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture4'] = $newfilename4;
                                }
                                
                                //indicate which file to resize (can be any type jpg/png/gif/etc...)
                                $file = 'img/uploads/'.$newfilename4;

                                //indicate the path and name for the new resized file
                                $resizedFile = 'img/uploads/images_resize/'.$newfilename4;
                                $this->smart_resize_image($file , 100 , 100 , false , $resizedFile , false , false ,100 );
                                $picture4 = new File(WWW_ROOT ."/img/uploads/images_resize/".$oldProduct[0]['Product']['picture4']);
                                $picture4->delete();
                                $picture4 = new File(WWW_ROOT ."/img/uploads/".$oldProduct[0]['Product']['picture4']);
                                $picture4->delete();
                            } else {
                                if (!empty($requestimage4['tmp_name'])) {
                                    $this->Product->invalidate('picture4', 'Please supply a valid image (.jpg, .gif or .png)');
                                    $validate = false;
                                } else {
                                    $this->request->data['Product']['picture4'] = NULL;
                                }
                            }
                       
			if ($this->Product->updateAll(
                                array( 
                                    'Product.category_id' => "'".$this->request->data['Product']['category_id']."'",
                                    'Product.user_id' => "'".$this->request->data['Product']['user_id']."'",
                                    'Product.title' => "'".$this->request->data['Product']['title']."'",
                                    'Product.status' => "'".$this->request->data['Product']['status']."'",
                                    'Product.type' => "'".$this->request->data['Product']['type']."'",
                                    'Product.price' => "'".$this->request->data['Product']['price']."'",
                                    'Product.description' => "'".$this->request->data['Product']['description']."'",
                                    'Product.location_id' => "'".$this->request->data['Product']['location_id']."'",
                                    'Product.address' => "'".$this->request->data['Product']['address']."'",
                                     'Product.name' => "'".$this->request->data['Product']['name']."'",
                                    'Product.phone' => "'".$this->request->data['Product']['phone']."'",
                                    'Product.email' => "'".$this->request->data['Product']['email']."'",
                                    'Product.picture1' => "'".$image1."'",
                                    'Product.picture2' => "'".$image2."'",
                                    'Product.picture3' => "'".$image3."'",
                                    'Product.picture4' => "'".$image4."'",
                                  
                                    'Product.expired_date' => "'".date('Y').'-0'.(date('m')+1).'-'.date("d H:i:s")."'",
                                    'Product.modified_date' => "'".date("Y-m-d H:i:s")."'"
                                ),
                                array( 'Product.id' => $id)
                            )) {
                            $this->Session->setFlash(__('The product has been saved.'));
                            if($this->Auth->user('role')=='Admin') {
                                 return $this->redirect(array('controller' => 'products','action' => 'index')); 
                            }
                            else {
                               return $this->redirect(array('controller' => 'posts','action' => 'manageads')); 
                            }
                            
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
			$this->request->data = $this->Product->find('first', $options);
		}
		 Controller::loadModel('Category');
                $nodelist = $this->Category->generateTreeList(null,null,null," - ");
               
//			$this->set('parents',$this->Category->generatetreelist());
                $this->set('parents',($nodelist));
		$categories = $this->Product->Category->find('list');
		$users = $this->Product->User->find('list');
		$locations = $this->Product->Location->find('list');
		$this->set(compact('users', 'locations'));
                $this->set('products', $this->Product->find('first', array('conditions'=>array('Product.id'=>$id))));
            }
             else {
                return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'index'));
            }
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
            if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
                $deletePro = $this->Product->find('all', array('conditions'=>array('Product.id'=>$id)));
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Product->delete()) {
			$this->Session->setFlash(__('The product has been deleted.'));
                        $picture1 = new File(WWW_ROOT ."/img/uploads/images_resize/".$deletePro[0]['Product']['picture1']);
                        $picture1->delete();
                        $picture2 = new File(WWW_ROOT ."/img/uploads/images_resize/".$deletePro[0]['Product']['picture2']);
                        $picture2->delete();
                        $picture3 = new File(WWW_ROOT ."/img/uploads/images_resize/".$deletePro[0]['Product']['picture3']);
                        $picture3->delete();
                        $picture4 = new File(WWW_ROOT ."/img/uploads/images_resize/".$deletePro[0]['Product']['picture4']);
                        $picture4->delete();
                        
                        $picture1 = new File(WWW_ROOT ."/img/uploads/".$deletePro[0]['Product']['picture1']);
                        $picture1->delete();
                        $picture2 = new File(WWW_ROOT ."/img/uploads/".$deletePro[0]['Product']['picture2']);
                        $picture2->delete();
                        $picture3 = new File(WWW_ROOT ."/img/uploads/".$deletePro[0]['Product']['picture3']);
                        $picture3->delete();
                        $picture4 = new File(WWW_ROOT ."/img/uploads/".$deletePro[0]['Product']['picture4']);
                        $picture4->delete();
                        
                        //Delete comment when delete product
                        $this->deleteComment($id);
                        
                        //Delete statistic when delete product
                        $this->deletestatistic($id);
		} else {
			$this->Session->setFlash(__('The product could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}else {
                return $this->redirect(array(
                                'controller' => 'product',
                                'action' => 'index'));
            }
}

/**
     * delete comment method
     *
     * @throws NotFoundException
     * 
     * 
     */

    public function deleteComment($id=null) {
        Controller::loadModel('Statistic');
        Controller::loadModel('Comment');
            $statisticData = $this->Comment->find('all', array('conditions' => array('Comment.product_id' => $id)));
            foreach ($statisticData as $value) {
                $this->Comment->id = $value['Comment']['id'];
		if (!$this->Comment->exists()) {
			throw new NotFoundException(__('Invalid comment'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Comment->delete()) {
			$this->Session->setFlash(__('The comment has been deleted.'));
		} else {
                    $this->Session->setFlash(__('The comment could not be deleted. Please, try again.'));
                }
            }
    }

/**
     * Delete statistic method
     *
     * @throws NotFoundException
     * 
     * 
     */
    public function deletestatistic($id) {
        Controller::loadModel('Statistic');
        Controller::loadModel('Product');
            $statisticData = $this->Statistic->find('all', array('conditions' => array('Statistic.product_id' => $id)));
            foreach ($statisticData as $value) {
                $this->Statistic->id = $value['Statistic']['id'];
                if (!$this->Statistic->exists()) {
                        throw new NotFoundException(__('Invalid statistic'));
                }
                $this->request->onlyAllow('post', 'delete');
                if ($this->Statistic->delete()) {
                        $this->Session->setFlash(__('The statistic has been deleted.'));
                } else {
                        $this->Session->setFlash(__('The statistic could not be deleted. Please, try again.'));
                }
            }
    }

/**
 * resize image method
 *
 * @throws NotFoundException
 * 
 * 
 */
public function smart_resize_image($file,
                              $width              = 0, 
                              $height             = 0, 
                              $proportional       = false, 
                              $output             = 'file', 
                              $delete_original    = true, 
                              $use_linux_commands = false,
  							  $quality = 100
  		 ) {
      
    if ( $height <= 0 && $width <= 0 ) return false;

    # Setting defaults and meta
    $info                         = getimagesize($file);
    $image                        = '';
    $final_width                  = 0;
    $final_height                 = 0;
    list($width_old, $height_old) = $info;
	$cropHeight = $cropWidth = 0;

    # Calculating proportionality
    if ($proportional) {
      if      ($width  == 0)  $factor = $height/$height_old;
      elseif  ($height == 0)  $factor = $width/$width_old;
      else                    $factor = min( $width / $width_old, $height / $height_old );

      $final_width  = round( $width_old * $factor );
      $final_height = round( $height_old * $factor );
    }
    else {
      $final_width = ( $width <= 0 ) ? $width_old : $width;
      $final_height = ( $height <= 0 ) ? $height_old : $height;
	  $widthX = $width_old / $width;
	  $heightX = $height_old / $height;

	  $x = min($widthX, $heightX);
	  $cropWidth = ($width_old - $width * $x) / 2;
	  $cropHeight = ($height_old - $height * $x) / 2;
    }

    # Loading image to memory according to type
    switch ( $info[2] ) {
      case IMAGETYPE_JPEG:  $image = imagecreatefromjpeg($file);  break;
      case IMAGETYPE_GIF:   $image = imagecreatefromgif($file);   break;
      case IMAGETYPE_PNG:   $image = imagecreatefrompng($file);   break;
      default: return false;
    }
    
    
    # This is the resizing/resampling/transparency-preserving magic
    $image_resized = imagecreatetruecolor( $final_width, $final_height );
    if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
      $transparency = imagecolortransparent($image);
      $palletsize = imagecolorstotal($image);

      if ($transparency >= 0 && $transparency < $palletsize) {
        $transparent_color  = imagecolorsforindex($image, $transparency);
        $transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
        imagefill($image_resized, 0, 0, $transparency);
        imagecolortransparent($image_resized, $transparency);
      }
      elseif ($info[2] == IMAGETYPE_PNG) {
        imagealphablending($image_resized, false);
        $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
        imagefill($image_resized, 0, 0, $color);
        imagesavealpha($image_resized, true);
      }
    }
    imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);


    # Taking care of original, if needed
    if ( $delete_original ) {
      if ( $use_linux_commands ) exec('rm '.$file);
      else @unlink($file);
    }

    # Preparing a method of providing result
    switch ( strtolower($output) ) {
      case 'browser':
        $mime = image_type_to_mime_type($info[2]);
        header("Content-type: $mime");
        $output = NULL;
      break;
      case 'file':
        $output = $file;
      break;
      case 'return':
        return $image_resized;
      break;
      default:
      break;
    }
    
    # Writing image according to type to the output destination and image quality
    switch ( $info[2] ) {
      case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
      case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
      case IMAGETYPE_PNG:
        $quality = 9 - (int)((0.9*$quality)/10.0);
        imagepng($image_resized, $output, $quality);
        break;
      default: return false;
    }

    return true;
  }
}
